<template>
  <div class="container">
    <el-row class="top-search">
      <el-col style="text-align: right;">
        <date-range-picker
          v-model="datePicker1"
          type="daterange"
          align="right"
          size="small"
          class="w-240"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          @change="timeChange"
        />
        <el-select v-model="listQuery.platform" size="small" class="w-140">
          <el-option
            v-for="item in options1"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select v-model="listQuery.appVersion" size="small" class="w-140">
          <el-option
            v-for="item in options2"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select v-model="listQuery.lang" size="small" class="w-140">
          <el-option
            v-for="item in options3"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select v-model="listQuery.country" size="small" class="w-140">
          <el-option
            v-for="item in options4"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="small"
          @click="search()"
          >搜索</el-button
        >
      </el-col>
    </el-row>
    <el-row class="p-t-15">
      <el-col>
        <el-tabs ref="tabs" v-model="activeName" type="card">
          <el-tab-pane label="新增用户实时分布" name="first">
            <div>
              <div class="title">
                <p>新增用户实时分布情况</p>
                <div class="btn">
                  <el-button
                    class="fr m-l-10"
                    size="small"
                    @click="toExport('add')"
                    >导出</el-button
                  >
                </div>
              </div>
              <div class="echart">
                <div id="add" :style="{ width: '100%', height: '480px' }" />
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="新增受邀用户" name="second">
            <div>
              <div class="title">
                <p>新增受邀用户分布</p>
                <div class="btn">
                  <el-button
                    class="fr m-l-10"
                    size="small"
                    @click="toExport('apprentice')"
                    >导出
                  </el-button>
                </div>
              </div>
              <div class="echart">
                <div
                  id="apprentice"
                  :style="{ width: echartWidth, height: '480px' }"
                />
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
    <div
      class="dividing-line"
      style="margin:10px 0; border: 1px solid #e6e6e6"
    />
    <el-row class="top-search">
      <el-col style="text-align: right;">
        <date-range-picker
          v-model="datePicker2"
          type="daterange"
          align="right"
          size="small"
          class="w-240"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          @change="timeChange2"
        />
        <el-select v-model="listQuery2.platform" size="small" class="w-140">
          <el-option
            v-for="item in options1"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select v-model="listQuery2.appVersion" size="small" class="w-140">
          <el-option
            v-for="item in options2"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select v-model="listQuery2.lang" size="small" class="w-140">
          <el-option
            v-for="item in options3"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select v-model="listQuery2.country" size="small" class="w-140">
          <el-option
            v-for="item in options4"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="small"
          @click="search2()"
          >搜索</el-button
        >
      </el-col>
    </el-row>
    <el-row class="p-t-15">
      <el-col>
        <el-tabs ref="tabs" v-model="activeName2" type="card">
          <el-tab-pane label="新增用户阅读资讯人数" name="three">
            <div>
              <div class="title">
                <p>新增用户阅读资讯人数</p>
                <div class="btn">
                  <el-button
                    class="fr m-l-10"
                    size="small"
                    @click="toExport('user')"
                    >导出</el-button
                  >
                </div>
              </div>
              <div class="echart">
                <div
                  id="user"
                  :style="{ width: echartWidth, height: '480px' }"
                />
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="新增会员阅读资讯人数" name="four">
            <div>
              <div class="title">
                <p>新增会员阅读资讯人数</p>
                <div class="btn">
                  <el-button
                    class="fr m-l-10"
                    size="small"
                    @click="toExport('member')"
                    >导出</el-button
                  >
                </div>
              </div>
              <div class="echart">
                <div
                  id="member"
                  :style="{ width: echartWidth, height: '480px' }"
                />
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import echarts from 'echarts';
import { dateShortcutKeyJS } from '@/mixins/index.js';
import timeUtils from '@/utils/timeHandle.js';
import { exportJsonToExcel, formatJson } from '@/utils/excel/Export2Excel';
import {
  getAppVersionListApi,
  getNewUserMemberListApi,
  getNewRelationshipChildListApi,
  getNewUserReadListApi,
  getNewMemberReadListApi
} from '@/api/user-analysis.js';
const HeadWithOutWeek = {
  add: [
    {
      prop: 'date',
      label: '时间'
    },
    {
      prop: 'newUserCount',
      label: '新增用户（人）'
    },
    {
      prop: 'newMemberCount',
      label: '新增会员（人）'
    }
  ],
  apprentice: [
    {
      prop: 'date',
      label: '时间'
    },
    {
      prop: 'newUserCount',
      label: '新增徒弟数（人）'
    }
  ],
  user: [
    {
      prop: 'date',
      label: '时间'
    },
    {
      prop: 'newUserReadCount',
      label: '新增用户阅读资讯人数（人）'
    },
    {
      prop: 'percent',
      label: '新增用户阅读转化率'
    }
  ],
  member: [
    {
      prop: 'date',
      label: '时间'
    },
    {
      prop: 'newUserReadCount',
      label: '新增会员阅读资讯人数（人）'
    },
    {
      prop: 'percent',
      label: '新增会员阅读转化率'
    }
  ]
};
const HeadWithWeek = {
  add: [
    {
      prop: 'date',
      label: '日期'
    },
    {
      prop: 'dayOfWeek',
      label: '星期'
    },
    {
      prop: 'newUserCount',
      label: '新增用户（人）'
    },
    {
      prop: 'newMemberCount',
      label: '新增会员（人）'
    }
  ],
  apprentice: [
    {
      prop: 'date',
      label: '日期'
    },
    {
      prop: 'dayOfWeek',
      label: '星期'
    },
    {
      prop: 'newUserCount',
      label: '新增徒弟数（人）'
    }
  ],
  user: [
    {
      prop: 'date',
      label: '日期'
    },
    {
      prop: 'dayOfWeek',
      label: '星期'
    },
    {
      prop: 'newUserReadCount',
      label: '新增用户阅读资讯人数（人）'
    },
    {
      prop: 'percent',
      label: '新增用户阅读转化率'
    }
  ],
  member: [
    {
      prop: 'date',
      label: '日期'
    },
    {
      prop: 'dayOfWeek',
      label: '星期'
    },
    {
      prop: 'newUserReadCount',
      label: '新增会员阅读资讯人数（人）'
    },
    {
      prop: 'percent',
      label: '新增会员阅读转化率'
    }
  ]
};
export default {
  mixins: [dateShortcutKeyJS],
  data() {
    return {
      tableName: {
        add: '新增用户实时分布',
        apprentice: '新增徒弟数',
        user: '新增用户阅读资讯人数',
        member: '新增会员阅读资讯人数'
      },
      dateType: {
        0: '(时)',
        1: '(天)',
        2: '(周)',
        3: '(月)'
      },
      options1: [
        {
          value: -1,
          label: '全部渠道'
        },
        {
          value: 1,
          label: 'Android'
        },
        {
          value: 2,
          label: 'IOS'
        }
      ],
      options2: [
        {
          value: null,
          label: '全部版本'
        }
      ],
      options3: [
        {
          value: -1,
          label: '全部系统语言'
        },
        {
          value: 1,
          label: '中文'
        },
        {
          value: 2,
          label: '柬文'
        },
        {
          value: 3,
          label: '英文'
        }
      ],
      options4: [
        {
          value: null,
          label: '所在地区'
        },
        {
          value: 'China',
          label: '中国'
        },
        {
          value: 'Cambodia',
          label: '柬埔寨'
        },
        {
          value: 'Other',
          label: '其他'
        }
      ],
      datePicker1: [
        timeUtils.timeHandle(new Date().getTime(), 'date'),
        timeUtils.timeHandle(new Date().getTime(), 'date')
      ],
      datePicker2: [
        timeUtils.timeHandle(
          new Date().getTime() - 3600 * 1000 * 24 * 6,
          'date'
        ),
        timeUtils.timeHandle(new Date().getTime(), 'date')
      ],
      listQuery: {
        startTime: null,
        endTime: null,
        lang: -1, // 操作语言 1:中文、2:柬文、3:英文
        platform: -1, // 渠道 1:安卓; 2:ios
        appVersion: null, // 版本
        country: null, // 地区
        dateType: 0 // 0:小时; 1:日期; 2:周;3:月;
      },
      listQuery2: {
        startTime: timeUtils.timeHandle(
          new Date().getTime() - 3600 * 1000 * 24 * 6,
          'date'
        ),
        endTime: timeUtils.timeHandle(new Date().getTime(), 'date'),
        lang: -1, // 操作语言 1:中文、2:柬文、3:英文
        platform: -1, // 渠道 1:安卓; 2:ios
        appVersion: null, // 版本
        country: null, // 地区
        dateType: 1 // 0:小时; 1:日期; 2:周;3:月;
      },
      activeName: 'first',
      activeName2: 'three',
      tableHead: null,
      list1: {
        date: [],
        dayOfWeek: [],
        newMemberCount: [],
        newUserCount: []
      },
      list2: {
        date: [],
        dayOfWeek: [],
        newUserCount: []
      },
      list3: {
        date: [],
        dayOfWeek: [],
        newUserCount: [],
        newUserReadCount: [],
        percent: []
      },
      list4: {
        date: [],
        dayOfWeek: [],
        newUserCount: [],
        newUserReadCount: [],
        percent: []
      },
      xData: [], // 保存x轴数据
      legend: {
        1: ['新增用户', '新增会员'],
        2: ['新增徒弟数'],
        3: ['阅读资讯人数', '阅读资讯转化率'],
        4: ['阅读资讯人数', '阅读资讯转化率']
      },
      exportData: {
        // 导出表格数据
        add: [],
        apprentice: [],
        user: [],
        member: []
      },
      echartWidth: null,
      isFirstRender: true
    };
  },
  created() {
    this.getAppVersion();
  },
  mounted() {
    this.getWidth();
    this.search();
    this.search2();
  },
  methods: {
    getAppVersion() {
      const that = this;
      getAppVersionListApi().then(res => {
        if (res.code == 200) {
          res.data.forEach(function(item) {
            const obj = {
              value: item,
              label: item
            };
            that.options2.push(obj);
          });
        }
      });
    },

    timeChange(time) {
      if (!time) return;
      const startTime = Date.parse(time[0]);
      const endTime = Date.parse(time[1]);
      const Days = Math.floor(
        Math.abs(endTime - startTime) / (24 * 3600 * 1000)
      );
      if (Days == 0) {
        this.listQuery.dateType = 0;
      } else if (Days <= 31) {
        this.listQuery.dateType = 1;
      } else if (Days > 31 && Days <= 48) {
        this.listQuery.dateType = 2;
      } else if (Days > 48) {
        this.listQuery.dateType = 3;
      }
    },

    timeChange2(time) {
      if (!time) return;
      const startTime = Date.parse(time[0]);
      const endTime = Date.parse(time[1]);
      const Days = Math.floor(
        Math.abs(endTime - startTime) / (24 * 3600 * 1000)
      );
      if (Days <= 30) {
        this.listQuery2.dateType = 1;
      } else if (Days > 30 && Days <= 48) {
        this.listQuery2.dateType = 2;
      } else if (Days > 48) {
        this.listQuery2.dateType = 3;
      }
    },

    getWidth() {
      this.$nextTick(function() {
        this.echartWidth = this.$refs['tabs'].$el.clientWidth + 'px';
      });
    },

    search() {
      if (!this.datePicker1) {
        this.$message.warning('请输入搜索时间', true);
        return;
      }

      this.listQuery.startTime = this.datePicker1[0];
      this.listQuery.endTime = this.datePicker1[1];

      this.getData1();
      this.getData2();
    },

    search2() {
      if (!this.datePicker2) {
        this.$message.warning('请输入搜索时间', true);
        return;
      }

      this.listQuery2.startTime = this.datePicker2[0];
      this.listQuery2.endTime = this.datePicker2[1];

      this.getData3();
      this.getData4();
    },

    getData1() {
      // 新增用户会员分析
      var myChart = echarts.init(document.getElementById('add'));
      myChart.showLoading();

      getNewUserMemberListApi(this.listQuery).then(res => {
        if (res.code == 200) {
          const getData = res.data;

          // 返回小时 拼接上日期
          if (this.listQuery.dateType == 0) {
            this.exportData.add = JSON.parse(JSON.stringify(res.data));
            this.exportData.add.forEach(item => {
              item.date = this.datePicker1[1] + ' ' + item.date + ':00 ';
            });
          } else {
            this.exportData.add = res.data;
          }

          Object.keys(this.list1).forEach(key => {
            this.list1[key] = getData.map(item => item[key]);
          });

          const that = this;
          that.xData = [];
          getData.forEach(function(item) {
            that.xData.push(item.date);
          });

          this.upDateEchart1();
        }
      });
    },

    upDateEchart1() {
      var myChart = echarts.init(document.getElementById('add'));
      myChart.showLoading();

      const option = {
        color: this.$store.state.app.eChartColor,
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        toolbox: {},
        legend: {
          data: this.legend[1],
          right: 60,
          top: 10
        },
        grid: {
          left: 60,
          right: 60
        },
        xAxis: [
          {
            name: this.dateType[this.listQuery.dateType],
            nameTextStyle: {
              padding: [40, 0, 18, 0]
            },
            type: 'category',
            data: this.xData, // x轴数据
            axisPointer: {
              type: 'shadow'
            }
          }
        ],
        yAxis: [
          {
            name: '(人)',
            type: 'value',
            min: 0,
            max: Math.ceil(Math.max(...this.list1['newUserCount'])),
            interval: Math.ceil(Math.max(...this.list1['newUserCount']) / 5),
            axisLabel: {
              formatter: '{value}'
            }
          },
          {
            name: '(人)',
            type: 'value',
            min: 0,
            max: Math.ceil(Math.max(...this.list1['newMemberCount'])),
            interval: Math.ceil(Math.max(...this.list1['newMemberCount']) / 5),
            axisLabel: {
              formatter: '{value}'
            }
          }
        ],
        series: [
          {
            name: '新增用户',
            type: 'line',
            data: this.list1['newUserCount']
          },
          {
            name: '新增会员',
            type: 'line',
            data: this.list1['newMemberCount'],
            yAxisIndex: 1
          }
        ]
      };
      myChart.setOption(option, true);
      myChart.hideLoading();
    },

    getData2() {
      // 新增徒弟数分布
      if (!this.isFirstRender) {
        var myChart = echarts.init(document.getElementById('apprentice'));
        myChart.showLoading();
      }
      getNewRelationshipChildListApi(this.listQuery).then(res => {
        if (res.code == 200) {
          const getData = res.data;

          // 返回小时 拼接上日期
          if (this.listQuery.dateType == 0) {
            this.exportData.apprentice = JSON.parse(JSON.stringify(res.data));
            this.exportData.apprentice.forEach(item => {
              item.date = this.datePicker1[1] + ' ' + item.date + ':00 ';
            });
          } else {
            this.exportData.apprentice = res.data;
          }

          Object.keys(this.list2).forEach(key => {
            this.list2[key] = getData.map(item => item[key]);
          });

          const that = this;
          that.xData = [];
          getData.forEach(function(item) {
            that.xData.push(item.date);
          });

          this.$nextTick(function() {
            this.upDateEchart2();
          });
        }
      });
    },

    upDateEchart2() {
      var myChart = echarts.init(document.getElementById('apprentice'));
      myChart.showLoading();

      const option = {
        color: this.$store.state.app.eChartColor,
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        toolbox: {},
        legend: {
          data: this.legend[2],
          right: 60,
          top: 10
        },
        grid: {
          left: 60,
          right: 60
        },
        xAxis: [
          {
            name: this.dateType[this.listQuery.dateType],
            type: 'category',
            data: this.xData, // x轴数据
            axisPointer: {
              type: 'shadow'
            }
          }
        ],
        yAxis: {
          name: '(人)'
        },
        series: [
          {
            name: '新增徒弟数',
            type: 'line',
            data: this.list2['newUserCount']
          }
        ]
      };
      myChart.setOption(option, true);
      myChart.hideLoading();
      this.isFirstRender = false;
    },

    getData3() {
      // 新增用户阅读资讯人数 userSelectType 1 用户
      var myChart = echarts.init(document.getElementById('user'));
      myChart.showLoading();

      const obj = Object.assign({}, this.listQuery2, { userSelectType: 1 });
      getNewUserReadListApi(obj).then(res => {
        if (res.code == 200) {
          const getData = res.data;
          this.exportData.user = res.data;

          // 百分数截掉后面的%
          getData.map(item => {
            return (item.percent = Number(item.percent.slice(0, -1)) || 0);
          });

          Object.keys(this.list3).forEach(key => {
            this.list3[key] = getData.map(item => item[key]);
          });

          const that = this;
          that.xData = [];
          getData.forEach(function(item) {
            that.xData.push(item.date);
          });

          this.upDateEchart3();
        }
      });
    },

    upDateEchart3() {
      var myChart = echarts.init(document.getElementById('user'));
      myChart.showLoading();

      const option = {
        color: this.$store.state.app.eChartColor,
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        toolbox: {},
        legend: {
          data: this.legend[3],
          right: 60,
          top: 10
        },
        grid: {
          left: 60,
          right: 60
        },
        xAxis: [
          {
            name: this.dateType[this.listQuery2.dateType],
            nameTextStyle: {
              padding: [42, 0, 18, 0]
            },
            type: 'category',
            data: this.xData, // x轴数据
            axisPointer: {
              type: 'shadow'
            }
          }
        ],
        yAxis: [
          {
            name: '(人)',
            type: 'value',
            min: 0,
            max: Math.ceil(Math.max(...this.list3['newUserReadCount'])),
            interval: Math.ceil(
              Math.max(...this.list3['newUserReadCount']) / 5
            ),
            axisLabel: {
              formatter: '{value}'
            }
          },
          {
            type: 'value',
            min: 0,
            max: 100,
            interval: 20,
            axisLabel: {
              formatter: '{value} %'
            }
          }
        ],
        series: [
          {
            name: '阅读资讯人数',
            type: 'bar',
            data: this.list3['newUserReadCount'],
            yAxisIndex: 0
          },
          {
            name: '阅读资讯转化率',
            type: 'line',
            data: this.list3['percent'],
            yAxisIndex: 1
          }
        ]
      };
      myChart.setOption(option, true);
      myChart.hideLoading();
    },

    getData4() {
      // 新增会员阅读资讯人数
      if (!this.isFirstRender) {
        var myChart = echarts.init(document.getElementById('member'));
        myChart.showLoading();
      }

      const obj = Object.assign({}, this.listQuery2, { userSelectType: 2 });
      getNewMemberReadListApi(obj).then(res => {
        if (res.code == 200) {
          const getData = res.data;
          this.exportData.member = res.data;

          // 百分数截掉后面的%
          getData.map(item => {
            return (item.percent = Number(item.percent.slice(0, -1)) || 0);
          });

          Object.keys(this.list4).forEach(key => {
            this.list4[key] = getData.map(item => item[key]);
          });

          const that = this;
          that.xData = [];
          getData.forEach(function(item) {
            that.xData.push(item.date);
          });

          this.$nextTick(function() {
            this.upDateEchart4();
          });
        }
      });
    },

    upDateEchart4() {
      var myChart = echarts.init(document.getElementById('member'));
      myChart.showLoading();

      const option = {
        color: this.$store.state.app.eChartColor,
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        toolbox: {},
        legend: {
          data: this.legend[4],
          right: 60,
          top: 10
        },
        grid: {
          left: 60,
          right: 60
        },
        xAxis: [
          {
            name: this.dateType[this.listQuery2.dateType],
            nameTextStyle: {
              padding: [42, 0, 18, 0]
            },
            type: 'category',
            data: this.xData, // x轴数据
            axisPointer: {
              type: 'shadow'
            }
          }
        ],
        yAxis: [
          {
            name: '(人)',
            type: 'value',
            min: 0,
            max: Math.ceil(Math.max(...this.list4['newUserReadCount'])),
            interval: Math.ceil(
              Math.max(...this.list4['newUserReadCount']) / 5
            ),
            axisLabel: {
              formatter: '{value}'
            }
          },
          {
            type: 'value',
            min: 0,
            max: 100,
            interval: 20,
            axisLabel: {
              formatter: '{value} %'
            }
          }
        ],
        series: [
          {
            name: '阅读资讯人数',
            type: 'bar',
            data: this.list4['newUserReadCount'],
            yAxisIndex: 0
          },
          {
            name: '阅读资讯转化率',
            type: 'line',
            data: this.list4['percent'],
            yAxisIndex: 1
          }
        ]
      };
      myChart.setOption(option, true);
      myChart.hideLoading();
    },

    toExport(exportName) {
      if (this.listQuery.dateType === 1) {
        this.tableHead = HeadWithWeek;
      } else {
        this.tableHead = HeadWithOutWeek;
      }

      const exprtTime = timeUtils.timeHandle(new Date().getTime(), 'date');
      const tHeader = this.tableHead[exportName].map(item => item.label);
      const tKey = this.tableHead[exportName].map(item => item.prop);
      const data = formatJson(tKey, this.exportData[exportName]); // 数据格式化
      const fileName = this.tableName[exportName] + exprtTime;
      exportJsonToExcel(tHeader, data, fileName); // 导出文件
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  padding: 15px;
  .w-140 {
    width: 140px;
  }
  .w-240 {
    width: 240px;
  }
  .title {
    height: 32px;
    position: relative;
    p {
      font-size: 22px;
      line-height: 32px;
      text-align: center;
    }
    .btn {
      width: 400px;
      height: 32px;
      position: absolute;
      right: 0;
      top: 0;
    }
  }
  .echart {
    width: 100%;
  }
  .search {
    text-align: right;
    padding: 15px;
    background-color: rgba(240, 242, 245, 1);
  }
  // 底部的echart
  .bottom-echart {
    .echart {
      position: relative;
      width: 45%;
      float: left;
      margin: 20px;
      .title {
        height: 32px;
        position: relative;
        p {
          font-size: 22px;
          line-height: 32px;
          text-align: center;
        }
        .btn {
          width: 400px;
          height: 32px;
          position: absolute;
          right: 0;
          top: 0;
        }
      }
      .num {
        position: absolute;
        right: 50px;
        bottom: 100px;
        li {
          font-size: 14px;
          line-height: 24px;
          span {
            padding: 0 10px;
          }
          .vertical {
            padding: 0;
            height: 24px;
            width: 1px;
            border: 1px solid #eee;
          }
        }
      }
      .list {
        width: 508px;
        padding-top: 20px;
        float: right;
        li {
          display: flex;
          justify-content: space-between;

          font-size: 22px;
          line-height: 48px;
          border-bottom: 1px solid #ccc;
        }
        .list-title {
          font-size: 18px;
          line-height: 56px;
        }
      }
    }
  }
}
</style>
